Week 8a
Advanced Plotting
Advanced plotting
I am just going to give you a little taste of what each of these packages can do. Please check out the documentation for each to delve deeper.
Lab
install.packages("patchwork") # for bringing plots together
install.packages("ggrepel") # for repelling labels
install.packages("gganimate") # animations
install.packages("magick") # for imageslibrary(tidyverse)
library(here)
library(patchwork)
library(ggrepel)
library(gganimate)
library(magick)
library(palmerpenguins)Easily bring your plots together
Let’s start with two simple plots from the Palmer penguin dataset.
Plot 1:
p1<-penguins %>%
ggplot(aes(x = body_mass_g,
y = bill_length_mm,
color = species))+
geom_point()
p1Plot 2:
p2<-penguins %>%
ggplot(aes(x = sex,
y = body_mass_g,
color = species))+
geom_jitter(width = 0.2)
p2p1 + p2p1+p2 +
plot_layout(guides = 'collect')plot_annotation
p1+p2 +
plot_layout(guides = 'collect')+
plot_annotation(tag_levels = 'A')use / instead of +
p1/p2 + #<<
plot_layout(guides = 'collect')+
plot_annotation(tag_levels = 'A')So many cool ways to bring together and modify plots. For more info see the many vignettes here
Easy and clear labels for plots
Use the mtcars dataset that comes with it. It is data on cars.
View(mtcars)using regular ‘geom_text’ causes a lot of overlap
ggplot(mtcars, aes(x = wt,
y = mpg,
label = rownames(mtcars))) +
geom_text() + # creates a text label
geom_point(color = 'red') Repel the labels
ggplot(mtcars, aes(x = wt,
y = mpg,
label = rownames(mtcars))) +
geom_text_repel() +
geom_point(color = 'red') repel labels
labels are put in a box
ggplot(mtcars, aes(x = wt,
y = mpg,
label = rownames(mtcars))) +
geom_label_repel() + # repel them
geom_point(color = 'red') For more cool things you can do with ggrepel see here
Make your figure an animation!
Let’s go back to our penguin plot, but animate the figure by year.
Our static plot.
penguins %>%
ggplot(aes(x = body_mass_g,
y = bill_depth_mm,
color = species)) +
geom_point() ‘transition_states’ year what are we animating by
transition_length The relative length of the transition
state_length The length of the pause between transitions
Here see one year at a time:
penguins %>%
ggplot(aes(x = body_mass_g,
y = bill_depth_mm,
color = species)) +
geom_point() +
transition_states(year,
transition_length = 2,
state_length = 1)